﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace Smartmanufact
{
     public class ServerClient
    {
        private const int BufferSize = 1024;
        private byte[] buffer;
        private TcpClient client;
        private NetworkStream streamToServer;
        private string msg = "Welcome to TraceFact.Net!";
        //private RequestHander hander = new RequestHander();

        public void Connect(IPAddress ip, int port)
        {
            try
            {
                client = new TcpClient();
                client.Connect(ip.ToString(), port);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
            buffer = new byte[BufferSize];

            //  打印连接到的服务端信息
            Console.WriteLine("Server Connnected!{0}-->{1}", client.Client.LocalEndPoint, client.Client.RemoteEndPoint);
            streamToServer = client.GetStream();

            lock (streamToServer)
            {
                AsyncCallback callback = new AsyncCallback(ReadComplete);
                streamToServer.BeginRead(buffer, 0, BufferSize, callback, null);
            }
            try
            {

                streamToServer = client.GetStream();
            }
            catch
            {

            }
        }
        // 连消息到服务器端
        public void SendMessage(string msg)
        {
            msg = msg.TrimEnd();
            Connetion_View.send_cmd = msg;
            int length = (msg.Length - 2) / 3 + 1;
            byte[] temp = new byte[length];
            if (length > 1)
            {
                byte mybyte = Convert.ToByte(msg.Substring(0, 2), 16);
                temp[0] = mybyte;
                for (int i = 1; i < length; i++)
                {
                    string a = msg.Substring(3 * i - 1, 2);
                    mybyte = Convert.ToByte(msg.Substring(3 * i, 2), 16);
                    temp[i] = mybyte;
                }
            }
            try
            {
                streamToServer.Write(temp, 0, temp.Length);
            }
            catch { }


            lock (streamToServer)
            {
                AsyncCallback callback = new AsyncCallback(ReadComplete);
                streamToServer.BeginRead(buffer, 0, BufferSize, callback, null);
            }
        }
        public void SendMessage()
        {
            SendMessage(this.msg);
        }

        // 读取完成时的回调方法

        private void ReadComplete(IAsyncResult ar)
        {
            int bytesRead;
            try
            {
                lock (streamToServer)
                {
                    bytesRead = streamToServer.EndRead(ar);
                }
                if (bytesRead == 0) throw new Exception("读取到了0字节");

                string msg = "";
                for (int i = 0; i < bytesRead; i++)
                {
                    msg = msg + buffer[i].ToString("X").PadLeft(2, '0') + " ";
                    //data.Array[i] = buffer[i];
                }

                Connetion_View.receive_cmd = msg;
                
                // 解析数据
                try
                {
                    if(buffer[5]==99 && buffer[6]==1 && buffer[7]==3 && buffer[8]==96)
                    {
                        int length=Connetion_View.byte_string.Length;
                        for(int i=0;i<length;i++)
                        {
                            int a = buffer[8 + 2 * i +1] * 256 + buffer[8 + 2 * i+2];
                            Connetion_View.byte_string[i] = a.ToString().PadLeft(4,'0');
                        }
                        int c = 0;
                        c = c + 1;
                    }
                }
                catch { }
                //
                lock (streamToServer)
                {
                    AsyncCallback callback = new AsyncCallback(ReadComplete);
                    streamToServer.BeginRead(buffer, 0, BufferSize, callback, null);
                }
            }
            catch (Exception ex)
            {
                if (streamToServer != null)
                    streamToServer.Dispose();
                client.Close();
                Console.WriteLine(ex.Message);
            }

        }


    }
}
